# 构建阶段
# 使用明确版本标签的基础镜像
FROM python:3.11-slim-bookworm AS builder

# 添加镜像拉取重试
RUN --mount=type=secret,id=dockerconfig,dst=/root/.docker/config.json \
    docker pull python:3.11-slim-bookworm || \
    (sleep 5 && docker pull python:3.11-slim-bookworm) || \
    (sleep 10 && docker pull python:3.11-slim-bookworm)

WORKDIR /app
ENV PYTHONFAULTHANDLER=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

COPY pyproject.toml .

# 安装构建依赖和项目依赖
# 精确控制安装版本
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    gcc=12.2.0-14 \
    python3-dev=3.11.2-1 && \
    pip install --user --no-deps -e . && \
    pip install --user --require-hashes -r <(pip list --format=freeze | grep -v '^media-info-process')

# 运行时阶段
FROM python:3.11-slim-bookworm

# 深度安全加固
RUN apt-get update && \
    apt-get upgrade -y --with-new-pkgs && \
    apt-get install -y --no-install-recommends \
    ca-certificates=20230311 \
    libssl3=3.0.11-1 && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* && \
    update-ca-certificates --fresh && \
    find / -xdev -type f -perm /u+s -exec chmod u-s {} \; && \
    find / -xdev -type f -perm /g+s -exec chmod g-s {} \;

WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .

# 确保脚本可执行
RUN chmod +x *.sh

# 应用运行时环境变量
ENV PATH=/root/.local/bin:$PATH \
    PYTHONPATH=/app

# 暴露多个服务端口
EXPOSE 5555 7860 8501

# 默认启动命令 (使用waitress运行)
CMD ["python", "./run_with_waitress.py", "--config", "./configs/config.json"]

# 构建和运行
# docker build -t media-info-process .
# docker run -p 5555:5555 media-info-process
# 运行容器时添加安全限制
# docker run -d \
#  --name media-service \
#  --memory="512m" \
#  --cpus="1" \
#  --read-only \
#  --security-opt="no-new-privileges" \
#  -p 5555:5555 \
#  media-info-process
# 挂载本地配置文件
# docker run -p 5555:5555 -v ${PWD}/configs/config.json:/app/configs/config.json media-info-process
# 查看日志
# docker logs -f <container_id>
# 扫描镜像
# docker scan media-info-process
# 更新基础镜像
# docker scout recommendations media-info-process
# docker pull python:3.11-slim-bookworm
# 查看漏洞
# docker scout cves media-info-process